<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRoute } from 'vue-router'
import { timeFormat } from '@/hooks/util'
import * as xyApi from '@/api/xy'
import { message } from 'ant-design-vue'
import Task from './components/Task.vue'
import RobotList from './components/RobotList.vue'
import TeskList from './components/TeskList.vue'

const route = useRoute()
const taskRef = ref()
const robotListRef = ref()
const TeskListRef = ref()

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  // console.log(page, pageSize)
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true,
})
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  [propName: string]: any
}
const searchParams = ref<SearchParams>({
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref([])
const columns = [
  {
    title: '任务状态',
    key: 'id',
    width: 300,
  },
  {
    title: '平台账号',
    key: 'robotList',
    width: 400,
  },
  {
    title: '上品信息',
    key: 'robotDayPutawayCount',
    width: 400,
  },
  {
    title: '院线 / 进度',
    key: 'limitList',
    width: 400,
  },
  {
    title: '备注 / 任务时间',
    key: 'remark',
    width: 400,
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    fixed: 'right',
  },
]

// 表格多选
const selectedRowKey = ref<Array<any>>([])
const selectedRow = ref<Array<object>>([])
const onSelectChange = (selectedRowKeys: any[], selectedRows: any[]) => {
  selectedRowKey.value = selectedRowKeys
  selectedRow.value = selectedRows
}

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize
  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

const getList = async () => {
  loading.value = true
  try {
    let { state, data, message: msg } = await xyApi.automatePutawayList(searchParams.value)
    if (state === 200) {
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

// 开关显示
const getStartState = computed(() => (state: number) => {
  return state == 1 ? true : false
})

// 开关切换
let switchLoading = ref<boolean>(false)
const changeState = async (id: string, status: number) => {
  switchLoading.value = true
  // console.log('status=', status)
  try {
    let { state, message: msg } = await xyApi.editAutomatePutawayState({
      automatePutawayId: id,
      startState: status == 1 ? 0 : 1,
    })
    if (state === 200) {
      message.success('修改成功')
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  switchLoading.value = false
}

let tipOpen = ref(false)
onMounted(() => {
  getList()

  tipOpen.value = true
})

const closeTipModal = () => {
  tipOpen.value = false
}

// 查询
const formRef = ref()
import type { SelectProps } from 'ant-design-vue'
const robotStateList = ref<SelectProps['options']>([
  {
    label: '正常',
    value: 1,
  },
  {
    label: '手动关闭',
    value: 0,
  },
])

interface FormState {
  remark?: string | undefined
  startState?: string | number
}
const formState = reactive<FormState>({})
const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.validate().then(() => {
    searchParams.value.remark = formState.remark || ''
    searchParams.value.startState = formState.startState
    getList()
  })
}

// 重置
const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.resetFields()
  for (let key in searchParams.value) {
    if (key != 'currentPage' && key != 'pageSize')
      searchParams.value.hasOwnProperty(key) && delete searchParams.value[key]
  }
  getList()
}

// 添加任务
const add = () => {
  taskRef.value.showModal()
}

// 机器人 / 院线列表
const showRobotList = (list: Array<any>, type: string) => {
  robotListRef.value.showModal(list, type)
}

// 任务记录
const showTeskList = (id: string) => {
  TeskListRef.value.showModal(id)
}

// 删除
const del = async (id: string) => {
  try {
    let { state, message: msg } = await xyApi.deleteAutomatePutaway({ id })
    if (state === 200) {
      message.success('删除成功')
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 备注
const EditRemarkSet = async (record: any) => {
  record.isRemarkShow = true
}
const editRemark = async (id: string, remark: string) => {
  const params = {
    automatePutawayId: id,
    remark,
  }
  try {
    let { state, message: msg } = await xyApi.editAutomatePutawayRemark(params)
    if (state === 200) {
      message.success('修改成功')
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
</script>

<template>
  <!-- <page-container :title="route.meta.title">
    <a-card style="overflow-x: scroll"> -->
  <div class="searchBox">
    <a-form ref="formRef" layout="inline" :model="formState" class="formClass">
      <a-form-item label="备注" name="remark">
        <a-input v-model:value="formState.remark" placeholder="备注" style="width: 200px" />
      </a-form-item>

      <a-form-item label="启动状态" name="startState">
        <a-select
          v-model:value="formState.startState"
          placeholder="请选择"
          style="width: 200px"
          allowClear
        >
          <a-select-option v-for="(item, index) in robotStateList" :key="index" :value="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item>
        <a-button type="primary" @click="search">搜索</a-button>
        <a-button @click="reset">重置</a-button>
        <a-button @click="add">添加任务</a-button>
      </a-form-item>
    </a-form>
  </div>

  <a-alert
    description="小提示：只要鼠标在表格上，按住左Shift键并滚动鼠标滚轮就可以横向滚动表格"
    type="info"
    banner
    style="margin-bottom: 10px; padding: 10px"
  />

  <a-table
    style="overflow-x: scroll"
    :columns="columns"
    :data-source="dataSource"
    :pagination="pagination"
    :loading="loading"
    @change="changePage"
    rowKey="id"
    :row-selection="{ selectedRowKeys: selectedRowKey, onChange: onSelectChange }"
    size="small"
    :scroll="{ x: 100 }"
  >
    <template #emptyText>
      <a-empty description="暂无数据" />
    </template>

    <template #headerCell="{ column }"></template>

    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'id'">
        <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
          <a-descriptions-item label="id">{{ record.id }}</a-descriptions-item>
          <a-descriptions-item label="启动状态">
            <a-switch
              :loading="switchLoading"
              :checked="getStartState(record.startState)"
              @change="changeState(record.id, record.startState)"
            />
          </a-descriptions-item>
        </a-descriptions>
      </template>

      <template v-else-if="column.key === 'robotList'">
        <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '160px' }">
          <a-descriptions-item label="平台账号">
            <div
              @click="showRobotList(record.robotList, 'robot')"
              style="
                cursor: pointer;
                display: -webkit-box;
                -webkit-line-clamp: 1;
                -webkit-box-orient: vertical;
                overflow: hidden;
              "
            >
              <a-tag color="blue" v-for="item in record.robotList">{{ item.name }}</a-tag>
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="每个闲鱼账号的间隔">
            {{ record.robotIntervalBeginTime }}分钟 ~ {{ record.robotIntervalEndTime }}分钟
          </a-descriptions-item>
        </a-descriptions>
      </template>

      <template v-else-if="column.key === 'robotDayPutawayCount'">
        <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '160px' }">
          <a-descriptions-item label="上品数量（个/天）">
            {{ record.robotDayPutawayCount }}
          </a-descriptions-item>
          <a-descriptions-item label="每次上品的间隔">
            {{ record.putawayIntervalBeginTime }}分钟 ~ {{ record.putawayIntervalEndTime }}分钟
          </a-descriptions-item>
        </a-descriptions>
      </template>

      <template v-else-if="column.key === 'limitList'">
        <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '160px' }">
          <a-descriptions-item label="选择的院线">
            <div
              @click="showRobotList(record.limitList, 'limit')"
              style="
                cursor: pointer;
                display: -webkit-box;
                -webkit-line-clamp: 1;
                -webkit-box-orient: vertical;
                overflow: hidden;
              "
            >
              <a-tag color="blue" v-for="item in record.limitList">{{ item.name }}</a-tag>
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="任务进度">
            <div style="display: flex">
              <a-progress :percent="record.ratio" :steps="20" size="small" />
              <QuestionCircleOutlined
                @click="showTeskList(record.id)"
                style="color: blue; position: relative; left: -50px"
              />
            </div>
          </a-descriptions-item>
        </a-descriptions>
      </template>

      <template v-else-if="column.key === 'remark'">
        <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
          <a-descriptions-item label="备注">
            <div style="display: flex; align-items: center">
              <a-tooltip placement="top" v-if="!record.isRemarkShow">
                <template #title>
                  <span>{{ record.remark }}</span>
                </template>
                <span class="hiddenText">{{ record.remark }}</span>
              </a-tooltip>
              <a-input
                v-else
                v-model:value="record.remark"
                @blur="editRemark(record.id, record.remark)"
                style="border: 0"
              />
              <EditOutlined
                @click="EditRemarkSet(record)"
                v-if="!record.isRemarkShow"
                style="margin-left: 6px; color: #1890ff"
              />
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="任务时间">
            {{ record.taskBeginTime }} - {{ record.taskEndTime }}
          </a-descriptions-item>
        </a-descriptions>
      </template>

      <template v-else-if="column.key === 'action'">
        <div style="width: 100px; margin: 0; padding: 0">
          <a-popconfirm title="确定删除?" ok-text="是" cancel-text="否" @confirm="del(record.id)">
            <a>删除</a>
          </a-popconfirm>
        </div>
      </template>
    </template>
  </a-table>

  <Task ref="taskRef" @refresh="getList"></Task>
  <RobotList ref="robotListRef"></RobotList>
  <TeskList ref="TeskListRef"></TeskList>
  <!-- </a-card>
  </page-container> -->

  <a-modal
    v-model:open="tipOpen"
    okText="已确认"
    @ok="closeTipModal"
    title="关于自动发布（影票代订业务）功能的使用提醒"
    :width="600"
  >
    <template #cancelText></template>
    <span>
      由于官方素材库内容有限，通过自动发布的商品标题、文案、图片素材，可能存在同质化，间接影响闲鱼的商品浏览，为保证您店铺的健康运营，建议您自行制作，标题，文案，图片等素材，进行发布
    </span>
  </a-modal>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  max-width: 140px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 16px;
}

.formClass {
  :nth-child(1) {
    margin-bottom: 1px;
  }
}

.searchBox {
  // margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}

.imgBox {
  width: 50px;
  height: 50px;

  img {
    height: 50px;
  }
}

.popoverImg {
  width: 300px;
  img {
    width: 100%;
  }
}
</style>
